package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @author LuoRis
 * @date 2021/03/05 17:01
 * @description 定时上架秒杀商品(存储到redis中)
 */
@Component
@Getter
@Setter
public class InitProductRedisJob implements SimpleJob {
    @Autowired
    private SeckillFeignApi seckillFeignApi;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 注入定时
     * 0/10 * * * * ?
     *
     * @return
     */
    @Value("${jobCron.initSeckillProduct}")
    private String cron;

    @Override
    public void execute(ShardingContext shardingContext) {
        doWork(shardingContext.getShardingParameter());
    }

    /**
     * 参数为 秒杀时间 分段
     *
     * @param shardingItem
     */
    private void doWork(String shardingItem) {
        Result<List<SeckillProductVo>> result = seckillFeignApi.queryCurrentlySeckillProduct(shardingItem);
        redisTemplate.delete(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(shardingItem));
        if (result != null && !result.hasError()) {
            List<SeckillProductVo> list = result.getData();
            if (list != null && list.size() > 0) {
                for (SeckillProductVo productVo : list) {
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(shardingItem), productVo.getId() + "", JSON.toJSONString(productVo));
                    redisTemplate.delete(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(productVo.getTime()+""));
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(productVo.getTime()+""),productVo.getId()+"",productVo.getStockCount()+"");
                    System.out.println("缓存成功");
                }
            }
        }
    }
}
